package es.mllacer.qqsm.runnables;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import es.mllacer.qqsm.util.Utils;

public class RemoteScoreRunnable implements Runnable {

	private static final String HIGH_SCORES_URI = "http://soletaken.disca.upv.es:8080/CMU/rest/highscores";

	private Activity activity = null;

	private int score = 0;

	public RemoteScoreRunnable(Activity activity) {
		this.activity = activity;
	}

	public void sendScore(int score) {
		this.score = score;
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		SharedPreferences settingsPrefs = activity.getSharedPreferences(
				Utils.SETTINGS_PREFERENCES, Context.MODE_PRIVATE);

		String name = settingsPrefs.getString(Utils.USER_PREFERENCE, "");
		float longitude = settingsPrefs.getFloat(Utils.LONGITUDE_PREFERENCE, 0);
		float latitude = settingsPrefs.getFloat(Utils.LATITUDE_PREFERENCE, 0);

		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, 3000);
		HttpConnectionParams.setSoTimeout(params, 5000);

		HttpClient client = new DefaultHttpClient(params);
		HttpPut request = new HttpPut(HIGH_SCORES_URI);

		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("name", name));
		pairs.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
		pairs.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
		pairs.add(new BasicNameValuePair("score", String.valueOf(score)));

		try {
			request.setEntity(new UrlEncodedFormEntity(pairs));
			client.execute(request);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
